package keypad

import (
	"sync"
	"time"

	"gitee.com/rw555/fdsmastergo/pkg/logger"
	"go.uber.org/zap"
)

// 需要实现的接口：Keypad 按键接口
type Keypad interface {
	// GetKeyState 获取按键状态
	GetKeyState(key Key) (KeyState, error)
}

// 需要实现的接口：KeyEventCallback 按键事件回调函数
type KeyEventCallback interface {
	OnShortPress(key Key)
	OnLongPress(key Key)
	OnSuperLongPress(key Key)
}

// KeyState 按键状态
type KeyState uint8

const (
	KeyReleased KeyState = iota
	KeyPressed
)

// Key 按键类型
type Key uint8

const (
	KeyMenu Key = iota
	KeyF1
	KeyF2
	KeyF3
	KeyMax
)

type KeyConfirmType int

const (
	KeyConfirmTypeShort KeyConfirmType = iota
	KeyConfirmTypeLong
	KeyConfirmTypeSuperLong
)

const (
	LongPressThreshold      = 3 * time.Second
	SuperLongPressThreshold = 6 * time.Second
)

type keyStatus struct {
	state     KeyState
	pressTime time.Time
}

// Scanner 按键扫描器接口
type Scanner interface {
	Start()
	Stop()
	SetCallback(callback KeyEventCallback)
}

// scanner 实现 Scanner 接口
type scanner struct {
	ticker    *time.Ticker
	quit      chan struct{}
	keypad    Keypad
	mu        sync.RWMutex
	keyStates map[Key]*keyStatus
	callback  KeyEventCallback
}

func NewScanner(keypad Keypad, callback KeyEventCallback) Scanner {
	s := &scanner{
		ticker:    time.NewTicker(50 * time.Millisecond),
		quit:      make(chan struct{}),
		keypad:    keypad,
		keyStates: make(map[Key]*keyStatus),
		callback:  callback,
	}
	return s
}

// Process 实现按键状态处理
func (h *scanner) Process(keypad Keypad) {
	for key := KeyMenu; key < KeyMax; key++ {
		state, err := keypad.GetKeyState(key)
		if err != nil {
			logger.SystemError("获取按键状态失败", zap.Error(err))
			continue
		}

		if state == KeyPressed {
			h.OnKeyPress(key)
		} else {
			h.OnKeyRelease(key)
		}
	}
}

// OnKeyPress 处理按键按下事件
func (h *scanner) OnKeyPress(key Key) {
	h.mu.Lock()
	defer h.mu.Unlock()

	if status, exists := h.keyStates[key]; exists {
		if status.state == KeyReleased {
			status.state = KeyPressed
			status.pressTime = time.Now()
		}
	} else {
		h.keyStates[key] = &keyStatus{
			state:     KeyPressed,
			pressTime: time.Now(),
		}
	}
}

// OnKeyRelease 处理按键释放事件
func (h *scanner) OnKeyRelease(key Key) {
	h.mu.Lock()
	defer h.mu.Unlock()

	if status, exists := h.keyStates[key]; exists && status.state == KeyPressed {
		status.state = KeyReleased
		duration := time.Since(status.pressTime)

		switch {
		case duration >= SuperLongPressThreshold:
			//logger.OperatorInfo("超长按触发",
			//	zap.String("key", key.String()),
			//	zap.Duration("duration", duration))
			h.callback.OnSuperLongPress(key)
		case duration >= LongPressThreshold:
			//logger.OperatorInfo("长按触发",
			//	zap.String("key", key.String()),
			//	zap.Duration("duration", duration))
			h.callback.OnLongPress(key)
		default:
			//logger.OperatorInfo("短按触发",
			//	zap.String("key", key.String()),
			//	zap.Duration("duration", duration))
			h.callback.OnShortPress(key)
		}
	}
}

func (s *scanner) Start() {
	logger.SystemInfo("开始扫描按键")
	go func() {
		for {
			select {
			case <-s.ticker.C:
				s.Process(s.keypad)
			case <-s.quit:
				s.ticker.Stop()
				return
			}
		}
	}()
}

func (s *scanner) Stop() {
	close(s.quit)
}

func (h *scanner) SetCallback(callback KeyEventCallback) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.callback = callback
}

func (k Key) String() string {
	switch k {
	case KeyMenu:
		return "菜单键"
	case KeyF1:
		return "F1"
	case KeyF2:
		return "F2"
	case KeyF3:
		return "F3"
	default:
		return "未知按键"
	}
}
